package com.atguigu.yygh.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.enums.PaymentStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WeiPayService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

/**
 * @author mgx
 * @version 1.0
 * @description: TODO
 * @date 2022/9/8 17:52
 */
@Api(tags = {"微信支付管理"})
@RestController
@RequestMapping("/user/order/weipay")
public class WeiPayController {

    @Autowired
    private WeiPayService weiPayService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private PaymentService paymentService;

    @GetMapping("/queryPayStatus/{orderId}")
    public R queryStatus(@PathVariable Long orderId) {
        // 根据订单id，向微信服务器查询订单是否已经支付成功
        Map<String, String> map = weiPayService.queryStatus(orderId);
        if(map == null) { // 查询失败 + 支付失败
            return R.error().message("查询失败");
        }
        if("SUCCESS".equals(map.get("trade_state"))) { // 支付成功 + 查询成功
            weiPayService.paymentSuccess(orderId, map);
            return R.ok();
        }
        return R.ok().message("支付中"); // 支付失败 + 未完成支付
    }

    @ApiOperation(value = "返回二维码")
    @GetMapping("/{orderId}")
    public R createNative(@PathVariable("orderId")Long orderId) {
        String codeUrl = weiPayService.createNative(orderId);
        return R.ok().data("url", codeUrl);
    }

}
